package com.simpleframe.web.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.simpleframe.env.Environment;
import com.simpleframe.exception.SimpleframeException;
import com.simpleframe.persistence.hibernate.Page;
import com.simpleframe.persistence.hibernate.Searcher;
import com.simpleframe.security.User;
import com.simpleframe.web.ActionMessage;
import com.simpleframe.web.DefaultActionMessage;
import com.opensymphony.xwork2.ActionContext;

public class SimpleframeAction implements ActionMessage {
	
	protected final Logger log = Logger.getLogger(this.getClass());
	public static final String MESSAGES_SESSION = "sessages_session";
	
	public final String SUCCESS = "success";
	public final String ERROR = "error";
	public final String INPUT = "input";
	public final String RESULT = "result";
	public final String LIST = "list";
	public final String GRID = "grid";
	public final String EDIT = "edit";
	public final String MAIN = "main";
	
	private ActionMessage actionMessage = new DefaultActionMessage();
	
	protected  Page page;
	
	protected int pageNo;
	
	protected int pageSize = 10;
	
	protected String pageOrder;
	
	protected Long[] ids;
	
	protected Date startDate;
	protected Date endDate;
	
	///这几个应自动完成
	protected String mode;
	protected String modeTitle;
	
	protected void setUpdateMode(){
		this.modeTitle="修改";
		this.mode = "update";
	}
	
	protected void setSaveMode(){
		this.modeTitle="添加";
		this.mode = "save";
	}
	
	public String getMode() {
		return mode;
	}
	
	public String getModeTitle() {
		return modeTitle;
	}
	
	protected void setAttribute(String name, Object o){
		getRequest().setAttribute(name, o);
	}

	protected HttpServletRequest getRequest(){
		return ServletActionContext.getRequest();
	}
	
	protected HttpServletResponse getResponse(){
		ActionContext.getContext().getSession();
		return ServletActionContext.getResponse();
	}
	
	protected Map<String, Object> getSession(){
		return ActionContext.getContext().getSession();
	}
	
	protected String getBasePath(){	
		return getRequest().getContextPath();
	}
	
	public void setIsNewQuery(String b){
		if(b.equals("true"))
			getSession().remove("conditions");
	}
	
	protected String error(String e){
		addError(e);
		if(isAjaxRequest()){
			return null;
		}
		return ERROR;
	}
	
	protected String success(String e){
		addMessage(e);
		if(isAjaxRequest()){
			return null;
		}
		return SUCCESS;
	}
	
	/**
	 * 当用户选择的页大于2时，加入
	 * @param pageNo
	 */
	@SuppressWarnings("unchecked")
	public void setPageNo(int pageNo) {
		//难度在这个时候，去添加进那个条件
		//conditions = (List)getSession().get("conditions");
		// TODO 难度在这个时候，去添加进那个条件
		this.pageNo = pageNo;
	}
	
	public Searcher getSearcher(){
		Searcher searcher = Searcher.create();
		searcher.setPageNo(pageNo);
		searcher.setPageSize(pageSize);
		searcher.setStartDate(startDate);
		searcher.setEndDate(endDate);
		searcher.setOrder(pageOrder);
		//搜索时的东东
		Map<String, String[]> values = ServletActionContext.getRequest().getParameterMap();
		System.out.println("获得所有表单内容");
		for (String name : values.keySet()) {
			System.out.println(name+":"+values.get(name));
			if(name.startsWith("#.")){
				String[] value = values.get(name);
				if (value.length > 1){
				   throw new SimpleframeException("搜索字引出现重复");
				}else{
					System.out.println(name.substring(2,name.length())+" "+value[0]);
					searcher.put(name.substring(2,name.length()), value[0]);
				}
			}
		}
		return searcher;
	}
	
	//页面处理
	/**
	 * 绕过Template,直接输出内容的简便函数.
	 */
	protected String render(String text, String contentType) {
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType(contentType);
			response.getWriter().write(text);
		} catch (IOException e) {
			System.out.println("直接输出内容出错");
		}
		return null;
	}
	
	/**
	 * 输出
	 * @param text
	 */
	protected void out(String text) {
		PrintWriter out = null;
		try {
			out = ServletActionContext.getResponse().getWriter();
			out.print(text);
		} catch (IOException e) {
			out.print("出错");
		}
	}
	
	/**
	 * 直接输出字符串.
	 */
	protected String renderText(String text) {
		return render(text, "text/plain;charset=UTF-8");
	}

	/**
	 * 直接输出字符串GBK编码.
	 */
	protected String renderHtml(String html) {
		return render(html, "text/html;charset=utf-8");
	}
	
	/**
	 * 判断客户端是不是 Ajax 请求，些方法只需要JS往heard 里添加值
	 * jquery 等框架都支持
	 * @return
	 */
	public boolean isAjaxRequest(){
		String XRequestWith = getRequest().getHeader("X-Requested-With");
		if("XMLHttpRequest".equals(XRequestWith)){
			return true;
		}
		return false;	
	}

	public User getSessionUser(){
		return (User)getSession().get(User.USER_SESSION);
	}

	/**
	 * 直接输出XML.
	 */
	protected String renderXML(String xml) {
		return render(xml, "text/xml;charset=UTF-8");
	}
	
	//@Override
	public void addError(String errorMessage) {
		actionMessage.addError(errorMessage);
	}

	//@Override
	public void addEvent(String name, String event) {
		actionMessage.addEvent(name, event);
	}

	//@Override
	public void addFieldError(String fieldName, String errorMessage) {
		actionMessage.addFieldError(fieldName, errorMessage);
	}

	//@Override
	/**
	 * 该方法用户，在保存或修改成功某一项数据时使用
	 * 步骤：创建Session信息
	 * 步骤：用签标显示后删除信息
	 * @param message
	 */
	public void addMessage(String message) {
		actionMessage.addMessage(message);
		ActionContext.getContext().getSession().put(MESSAGES_SESSION, actionMessage.getMessages());
		
	}
	
	//@Override
	public boolean hasError() {
		return actionMessage.hasError();
	}
	
	//@Override
	public boolean hasFieldError() {
		return actionMessage.hasFieldError();
	}
	
	//@Override
	public Map<String, List<String>> getFieldErrors() {
		return actionMessage.getFieldErrors();
	}
	
	//@Override
	public Collection<String> getErrors() {
		return actionMessage.getErrors();
	}
	
	//@Override
	public Collection<String> getFieldErrorMessages() {
		return actionMessage.getFieldErrorMessages();
	}

	//@Override
	public Collection<String> getMessages() {
		return actionMessage.getMessages();
	}
	
	/**
	 * 用于struts2配置文件，解决服务器代理转发问题
	 */
	public String getCtx(){
		return (String) getRequest().getAttribute(Environment.ENV_CTX_KEY);
	}

	//@Override
	public boolean hasMessage() {
		return actionMessage.hasMessage();
	}
	
	//setters and getters
	public Page getPage() {
		return page;
	}

	public void setPage(Page page) {
		this.page = page;
	}
	
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public String getPageOrder() {
		return pageOrder;
	}
	
	public void setPageOrder(String pageOrder) {
		this.pageOrder = pageOrder;
	}
	
	public void setIds(Long[] ids) {
		this.ids = ids;
	}

	public Date getStartDate() {
		return startDate;
	}

	public Date getEndDate() {
		return endDate;
	}
	
	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}
}
